package com.demo.shangguigu.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;


public class CompletableFutureAPIDemo
{
    public static void main(String[] args) throws ExecutionException, InterruptedException
    {
        CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
            System.out.println("执行结构");
//            try {
//                Thread.sleep(2000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            int a=0;
            int b=10/0;
            if(a==0){
                return "err";
            }else{
                return "1";
            }


        }).handle((a,b)->{
            try {
                Thread.sleep(5000);
            }catch (Exception e){

            }
            System.out.println("handle param a->" + a + ",b->" + b);
            return "rr";
        });

        CompletableFuture<Integer> cf2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("执行结构2");
            return 2;
        });
        CompletableFuture<String> cf3 = cf.thenCombine(cf2, (a,b) -> {
            System.out.println("job4 param a->" + a + ",b->" + b);
                if(a.equals("err")){
                    throw new RuntimeException();
                }
            return "ok";
        }).handle((a,b)->{
            System.out.println("job5 param a->" + a + ",b->" + b);
            return "kk";
        });
        System.out.println("cf3---"+cf3.get());
        System.out.println("------");

    }

    /**
     * 获得结果和触发计算
     * @throws InterruptedException
     * @throws ExecutionException
     */
    private static void group1() throws InterruptedException, ExecutionException
    {
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            //暂停几秒钟线程
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "abc";
        });

        //System.out.println(completableFuture.get());
        //System.out.println(completableFuture.get(2L,TimeUnit.SECONDS));
        //System.out.println(completableFuture.join());

        //暂停几秒钟线程
        //try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }

        //System.out.println(completableFuture.getNow("xxx")); // 相当于备胎值 没有获取返回结果之前 先返回该值
        System.out.println(completableFuture.complete("completeValue")+"\t"+completableFuture.get());
    }
}
